﻿using ChoJu.ModelManager.Config;
using ChongJu.GlobalInfo;
using ChongJu.ImageAnalyze;
using NModbus;
using Public.Logger;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net.Sockets;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Timers;
using System.Windows.Threading;

namespace ChoJu.Single.DAL
{
    public class WeightDal
    {
        private IModbusMaster _master;
        private List<double> _lstWeis;
        private double _lastWeight = -100;

        public double CurrentWeight { get; private set; }


        private double _max = -1;
        private double _min = 100;
        private double _sum = 0;

        private double _result = -100;

        private static readonly object _obj = new object();
        private static WeightDal _instance;
        public static WeightDal Instance
        {
            get
            {
                if (_instance == null)
                    lock (_obj)
                        if (_instance == null)
                            _instance = new WeightDal();

                return _instance;
            }
        }

        private StringBuilder _sb = new StringBuilder();
        private bool _bol = false;

        private WeiCalca _dal;
        private WeightConfigModel _config;

        public WeightDal()
        {
            _lstWeis = new List<double>();
        }


        public bool Init(WeightConfigModel config)
        {
            try
            {
                string ipAddress = "192.168.10.30";
                int port = 502;
                ushort startAddress = 6004; // Modbus寄存器地址
                byte slaveId = 1;           // 从站地址

                _config = config;
                _dal = new WeiCalca(config.Count, config.SmoothCount, config.Change);

                try
                {
                    if (_master == null)
                        _bol = true;
                    else
                    {
                        _bol = false;
                        Thread.Sleep(1000);
                        _bol = true;
                    }

                    // 创建TCP客户端连接
                    TcpClient client = new TcpClient(ipAddress, port);
                    // 创建Modbus主站
                    var factory = new ModbusFactory();
                    _master = factory.CreateMaster(client);
                    Start(slaveId, startAddress);
                }
                catch (Exception ex)
                {
                    Logger.Error("初始化称重异常", ex);
                    return false;
                }

                return true;
            }
            catch (Exception ex)
            {
                return false;
            }
        }
        private void Start(byte slaveId, ushort startAddress)
        {
            Task.Run(() =>
            {
                while (_bol)
                {
                    var result = Math.Round(ReadDifferentDataTypes(_master, slaveId, startAddress), 2);
                    CurrentWeight = result;
                    _result = _dal.InputNew(result);

                    Thread.Sleep(_config.Interval);
                }
            });
        }

        public double GetWeight()
        {
            //DateTime dt = DateTime.Now;
            //_bol = true;
            while(_result == -100)
                Thread.Sleep(_config == null ? 10 : _config.Interval);

            //_bol = false;
            //System.IO.File.WriteAllText(System.IO.Path.Combine(AppContext.BaseDirectory, "weight.txt"), _sb.ToString());
            //_sb.Clear();
            //tm = (DateTime.Now - dt).TotalMilliseconds;
            return _result;
            
        }

        public double GetCurrentWeight()
        {
            if (_dal == null)
                return 0;

            return _dal.GetCurrentWeight();
        }

        private double ReadDifferentDataTypes(IModbusMaster master, byte slaveId, ushort address)
        {
            try
            {
                // 读取两个寄存器（32位整数）
                ushort[] twoRegisters = master.ReadHoldingRegisters(slaveId, address, 2);

                // 读取两个寄存器（浮点数）
                byte[] bytes = new byte[4];
                Buffer.BlockCopy(twoRegisters, 0, bytes, 0, 4);
                double floatValue = BitConverter.ToSingle(bytes, 0);

                return floatValue;
            }
            catch (Exception ex)
            {
                return -1;
            }
        }

        public void Pleed()
        {
            _master.WriteSingleRegister(1, 6007, 256);
            Thread.Sleep(100);
            _master.WriteSingleRegister(1, 6007, 0);
        }
    }

}
